﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;

namespace YJ.Cache.InProc
{
    /// <summary>
    /// .net自带缓存类
    /// </summary>
    public class Cache : Interface.ICache
    {
        private static readonly object lockobj = new object();
        //private static System.Web.Caching.Cache cache = null == System.Web.HttpContext.Current ? null : System.Web.HttpContext.Current.Cache;
        private static System.Web.Caching.Cache _cache;
        private static System.Web.Caching.Cache cache 
        {
            get {
                if (null != _cache)
                {
                    return _cache;
                }
                else
                {
                    if (null != System.Web.HttpContext.Current)
                    {
                        _cache = System.Web.HttpContext.Current.Cache;
                        return _cache;
                    }
                }
                return null;
            }
        }
        /// <summary>
        /// 插入缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Insert(string key, object obj)
        {
            if (obj == null || cache == null) return false;
            lock (lockobj)
            {
                cache.Insert(key, obj, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
            }
            return true;
        }
        /// <summary>
        /// 插入缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Insert(string key, object obj, DateTime expiry)
        {
            if (obj == null || cache == null) return false;
            lock (lockobj)
            {
                cache.Insert(key, obj, null, expiry, System.Web.Caching.Cache.NoSlidingExpiration,
                    System.Web.Caching.CacheItemPriority.Normal, null);
            }
            return true;
        }
        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public object Get(string key)
        {
            if (cache == null) return null;
            return cache.Get(key);
        }
        /// <summary>
        /// 移出缓存
        /// </summary>
        /// <param name="key"></param>
        public bool Remove(string key)
        {
            if (cache == null) return false;
            lock (lockobj)
            {
                cache.Remove(key);
            }
            return true;
        }
        /// <summary>
        /// 移出所有缓存
        /// </summary>
        /// <returns></returns>
        public void RemoveAll()
        {
            for (int i = 0; i < cache.Count; i++)
            { 
               
            }
        }
    }
}
